package chapter5;

/**
 * wait()和notify()的示例
 * Created by LinGer on 2019/6/17
 */
public class ThreadA extends Thread{

    public ThreadA(String name){
        super(name);
    }

    @Override
    public void run() {
        synchronized (this){
            System.out.println(getName() + " call notify()");
            //wait、notify、notifyAll都需要在同步方法/代码块中调用
            notify();
        }
    }


    public static void main(String[] args) {
        ThreadA t1 = new ThreadA("t1");

        //main获取t1的同步锁
        synchronized (t1){
            try {
                //启动线程t1
                System.out.println(Thread.currentThread().getName() + " start t1");
                t1.start();

                //**主线程** 等待t1通过notify唤醒
                System.out.println(Thread.currentThread().getName() + " wait()");
                //主线程释放掉t1对象的同步锁，进入阻塞状态。等待t1对象上的线程通过notify将其唤醒
                t1.wait();
                System.out.println(Thread.currentThread().getName() + " continue");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
